8520. Conditional statement - 1

 

Find the value of y according to the following condition:

 

Input. One integer x (-1000 ≤ x ≤ 1000).

 

Output. Print the value of y according to the given condition.

 

Sample input 1

Sample output 1

2

2

 

 

Sample input 2

Sample output 2

10

17

 

 

SOLUTION

conditional statement

 

Algorithm analysis

Use a conditional statement to solve the problem. Since -1000 ≤ x ≤ 1000, it’s sufficient to use the int type.

 

Algorithm implementation

Read the input value of x.

 

scanf("%d", &x);

 

Compute the value of y.

 

if (x < 5)

  y = x * x – 3 * x + 4;

else

  y = x + 7;

 

Print the result.

 

printf("%d\n",y);

 

Algorithm implementation – ternary operator

Read the input value of x.

 

scanf("%d", &x);

 

Compute the value of y.

 

y = (x < 5) ? x * x – 3 * x + 4 : x + 7;

 

Print the result.

 

printf("%d\n",y);

 

Java implementation

 

import java.util.*;

 

public class Main

{

  public static void main(String[] args)

  {

    Scanner con = new Scanner(System.in);

    int y, x = con.nextInt();

    if (x < 5)

      y = x*x - 3*x + 4;

    else

      y = x + 7;

    System.out.println(y);

    con.close();

  }

}  

 

Python implementation

Read the input value of x.

 

x = int(input())

 

Compute the value of y.

 

if x < 5:

  y = x*x - 3*x + 4

else:

  y = x + 7

 

Print the result.

 

print(y)

 

Go implementation

 

package main

 

import "fmt"

 

func main() {

  var x, y int

  fmt.Scanf("%d",&x)

 

  if x < 5 {

    y = x*x - 3*x + 4

  } else {

    y = x + 7

  }

 

  fmt.Println(y)

}

 

C# implementation

 

using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.Threading.Tasks;

 

namespace ConsoleAppCSharp

{

  class Program

  {

    static void Main(string[] args)

    {

      int x, y;

      x = Convert.ToInt32(Console.ReadLine());

      if (x >= 5)

        y = x + 7;

      else

        y = x * x - 3 * x + 4;

      Console.WriteLine("{0}", y);

    }

  }

}